package com.sky.utils;

import io.minio.*;
import io.minio.errors.MinioException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


@Data
@AllArgsConstructor
@Slf4j
public class MinioUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

   public String upload(byte[] bytes,String objectName){
       try{
       MinioClient minioClient =MinioClient.builder()
               .endpoint(endpoint) // MinIO 服务的端点
               .credentials(accessKeyId, accessKeySecret) // 访问密钥和秘密密钥
               .build();
       minioClient.putObject(
                   PutObjectArgs.builder()
                           .bucket(bucketName) // 存储桶名称
                           .object(objectName) // 对象名称
                           .stream(new ByteArrayInputStream(bytes), bytes.length, -1) // 输入流和长度
                           .build()
           );
       } catch (MinioException oe) {

       } catch (IOException e) {
           throw new RuntimeException(e);
       } catch (NoSuchAlgorithmException e) {
           throw new RuntimeException(e);
       } catch (InvalidKeyException e) {
           throw new RuntimeException(e);
       }
       StringBuilder stringBuilder = new StringBuilder();
       stringBuilder
               .append(endpoint)
               .append("/")
               .append(bucketName)
               .append("/")
               .append(objectName);

       log.info("文件上传到:{}", stringBuilder.toString());

       return stringBuilder.toString();
   }
}